<template>
  <div>
    <a-form
      ref="FormRef"
      :model="FormState"
      :rules="FormRule"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
    >
      <a-form-item label="邮件服务器" has-feedback required name="es_id">
        <a-select v-model:value="FormState.es_id" placeholder="请选择邮件服务器">
          <a-select-option v-for="d in allServer" :key="d._id" :value="d._id">
            {{ d.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="邮件模版" name="et_id">
        <a-select v-model:value="FormState.et_id" placeholder="请选择邮件模版">
          <a-select-option key="" value="">不选择</a-select-option>
          <a-select-option v-for="d in allTpl" :key="d._id" :value="d._id">
            {{ d.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="邮箱地址" has-feedback required name="email">
        <a-textarea
          v-model:value="FormState.email"
          :rows="15"
          placeholder="请输入邮箱地址，一行一个，格式：邮箱地址|收件人（可选）"
        />
      </a-form-item>
      <a-form-item label="邮件标题" name="title">
        <a-input v-model:value="FormState.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="自动去重" has-feedback>
        <a-switch
          v-model:checked="FormState.is_filter_bool"
          checked-children="是"
          un-checked-children="否"
        />
      </a-form-item>
      <a-form-item v-if="FormState.is_filter_bool" label="去重标识" name="filter_id">
        <a-input-search
          v-model:value="FormState.filter_id"
          placeholder="请输入自定义去重标识，系统将根据标识自动过滤已发送邮箱"
          style="width: 100%"
          enter-button="随机生成"
          @search="getFilterId"
        />
      </a-form-item>
      <a-form-item label="邮件内容" has-feedback required name="content">
        <a-textarea
          v-model:value="FormState.content"
          :rows="15"
          placeholder="请输入邮件内容，支持HTML"
        />
      </a-form-item>
      <a-form-item style="margin-left: 12.5%">
        <a-button type="primary" html-type="submit" :loading="ConfirmLoading" @click="OnSubmit">
          发送
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">/* eslint-disable */
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import { Row, Col, Switch } from 'ant-design-vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { doSendEmail, getAllServerList, getAllTplList } from '@/api/email'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'ItemEdit',
  components: {
    PlusOutlined,
    LoadingOutlined,
    [Row.name]: Row,
    [Switch.name]: Switch,
    [Col.name]: Col
  },
  setup() {
    const FormRef = ref()
    const router = useRouter()
    const state = reactive({
      ConfirmLoading: false,
      allServer: [],
      allTpl: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      }
    })
    const FormState = reactive({
      es_id: '',
      title: '',
      et_id: '',
      email: '',
      filter_id: '',
      content: '',
      is_filter_bool: true
    })
    const FormRule = {
      es_id: [
        { required: true, message: '请选择邮件服务器', trigger: ['blur', 'change'] }
      ],
      filter_id: [
        { required: FormState.is_filter_bool === true, message: '请输入自定义去重标识', trigger: ['blur', 'change'] }
      ],
      email: [{ required: true, message: '请输入邮箱地址，一行一个', trigger: ['blur', 'change'] }],
      end_time: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }],
      content: [{ required: true, message: '请输入邮件内容，支持HTML', trigger: ['blur', 'change'] }],
      is_filter_bool: [
        { required: true, message: '请输入序号', trigger: ['blur', 'change'], type: 'number' }
      ]
    }
    onMounted(() => {
      getServerList()
      getTplList()
    })
    const getServerList = () => {
      getAllServerList({}).then((res) => {
        state.allServer = res
      })
    }
    const getTplList = () => {
      getAllTplList({}).then((res) => {
        state.allTpl = res
      })
    }
    function createRandomChar(c = 'a-z') {
      switch (c) {
        case 'A-Z':
          return String.fromCharCode(Math.trunc(Math.random() * 25) + 65);
        case 'a-z':
          return String.fromCharCode(Math.trunc(Math.random() * 25) + 97);
        case '0-9':
        default:
          return String.fromCharCode(Math.trunc(Math.random() * 10) + 48);
      }
    }
    const getFilterId = () => {
      let str = '';
      for (let i = 0; i < 18; i++) str += createRandomChar();
      FormState.filter_id = str
    }
    const OnSubmit = () => {
      FormRef.value
        .validate()
        .then(() => {
          doSendEmail(toRaw(FormState))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.ConfirmLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    return {
      ...toRefs(state),
      FormRef,
      getServerList,
      FormState,
      FormRule,
      getFilterId,
      OnSubmit
    }
  }
})
</script>

<style scoped></style>
